package com.lanju.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.lanju.common.SnowflakeIdWorker;
import com.lanju.common.SpringUtils;
import com.lanju.entity.Contract;
import com.lanju.entity.ExpectedFixedIncome;
import com.lanju.entity.User;
import com.lanju.entity.VacantPeriod;
import com.lanju.service.ContractService;
import com.lanju.service.ZuKeContractService;
import com.lanju.util.ObjAndMapUtil;
/**
 * 新版合同
 * @author zqd
 *
 */
@Controller
@RequestMapping("/contract")
public class ContractController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ContractController.class);
	
	@Autowired
	ContractService contractService;
	
	@Autowired
	ZuKeContractService zuKeContractService;
	
	/**
	 * 创建合同
	 * @param request
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping("/createContract")
	@ResponseBody
	public  Map<String,Object> createContract(HttpServletRequest request ,HttpServletResponse response) throws ParseException{
		 Map<String, Object> param = SpringUtils.getParameterMap(request);
		 JSONObject json = JSONObject.fromObject(param);
		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		 Contract contract=(Contract)JSONObject.toBean(json, Contract.class);
		 if(param.get("contractStartTime") !=null)contract.setContractStartTime(sdf.parse(param.get("contractStartTime").toString()));
		 if(param.get("contractEndTime") !=null)contract.setContractEndTime(sdf.parse(param.get("contractEndTime").toString()));
		 if(param.get("signDate") !=null)contract.setSignDate(sdf.parse(param.get("signDate").toString()));
		 if(param.get("deliveryHouseTime") !=null)contract.setDeliveryHouseTime(sdf.parse(param.get("deliveryHouseTime").toString()));
		 if(param.get("firstAccountTime") !=null)contract.setFirstAccountTime(sdf.parse(param.get("firstAccountTime").toString()));
		 if(param.get("firstMngStartTime") !=null)contract.setFirstMngStartTime(sdf.parse(param.get("firstMngStartTime").toString()));
		 if(param.get("serviceStartTime") !=null)contract.setServiceStartTime(sdf.parse(param.get("serviceStartTime").toString()));
		 contract.setCreateTime(new Date());
		 contract.setUpdateTime(new Date());
		 SnowflakeIdWorker idWorker = new SnowflakeIdWorker(RandomUtils.nextLong(0,31), RandomUtils.nextLong(0,31));
		 contract.setContractId("HT-"+idWorker.nextId());
		 contract.setStatus(-1);
		 String income=param.get("incomeArr")==null?null:param.get("incomeArr").toString();
		 if(income!=null){
		 JSONArray incomeArr=com.alibaba.fastjson.JSONObject.parseArray(income);
		 for(int i=0;i<incomeArr.size();i++){
			 Object obj=incomeArr.get(i);
			 try {
				Map<String,Object> incomeMmap=(Map<String, Object>) ObjAndMapUtil.objectToMap(obj).get("innerMap");
				ExpectedFixedIncome expectIncome=new ExpectedFixedIncome();
				expectIncome.setExpectedEndTime(sdf.parse(incomeMmap.get("expectedEndTime").toString()));
				expectIncome.setExpectedStartTime(sdf.parse(incomeMmap.get("expectedStartTime").toString()));
				expectIncome.setIncome(Integer.valueOf(incomeMmap.get("income").toString()));
				expectIncome.setIncomeId("i-"+idWorker.nextId());
				contract.getExpectedFixedIncomeSet().add(expectIncome);
				contract.setExpectedFixedIncomeSet(contract.getExpectedFixedIncomeSet());
				expectIncome.setContract(contract);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		
		 }
		 String vacantPeriod=param.get("vacantPeriodArr")==null?null:param.get("vacantPeriodArr").toString();
		 if(vacantPeriod!=null){
		 JSONArray vacantPeriodArr=com.alibaba.fastjson.JSONObject.parseArray(vacantPeriod);
		 for(int i=0;i<vacantPeriodArr.size();i++){
			 Object obj=vacantPeriodArr.get(i);
			 try {
				Map<String,Object> vMmap=(Map<String, Object>) ObjAndMapUtil.objectToMap(obj).get("innerMap");
				VacantPeriod vacantPeriod1=new VacantPeriod();
				vacantPeriod1.setStartTime(sdf.parse(vMmap.get("startTime").toString()));
				vacantPeriod1.setEndTime(sdf.parse(vMmap.get("endTime").toString()));
				vacantPeriod1.setVid("v-"+idWorker.nextId());
				contract.getVacantPeriodSet().add(vacantPeriod1);
				contract.setVacantPeriodSet(contract.getVacantPeriodSet());
				vacantPeriod1.setContract(contract);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		
		 }
		 return contractService.createContract(contract);
	}
	/**
	 * 删除合同
	 * @param request
	 * @return
	 */
	@RequestMapping("/delContract")
	@ResponseBody
	public Map<String,Object> delContract(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		return contractService.delContract(param);
	}
	/**
	 * 获取合同详情
	 * @return
	 */
	@RequestMapping("/getConstractDetailById")
	@ResponseBody
	public Map<String,Object> getConstractDetailById(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		User user =(User) session.getAttribute("userModel");
		if(user !=null){
			param.put("flag", user.getFlag());
			param.put("login", true);
		}else{
			param.put("flag","1");
			param.put("login", false);
		}
		return contractService.getConstractDetailById(param);
	}
	/**
	 * 更新合同
	 * @param request
	 * @return
	 * @throws ParseException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/updateConstract")
	@ResponseBody
	public Map<String,Object> updateConstract(HttpServletRequest request,HttpServletResponse response) throws ParseException{
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		JSONObject json = JSONObject.fromObject(param);
		SnowflakeIdWorker idWorker = new SnowflakeIdWorker(RandomUtils.nextLong(0,31), RandomUtils.nextLong(0,31));
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		Contract contract=(Contract)JSONObject.toBean(json, Contract.class);
		if(param.get("contractStartTime") !=null)contract.setContractStartTime(sdf.parse(param.get("contractStartTime").toString()));
		if(param.get("contractEndTime") !=null)contract.setContractEndTime(sdf.parse(param.get("contractEndTime").toString()));
		if(param.get("signDate") !=null)contract.setSignDate(sdf.parse(param.get("signDate").toString()));
		if(param.get("deliveryHouseTime") !=null)contract.setDeliveryHouseTime(sdf.parse(param.get("deliveryHouseTime").toString()));
		if(param.get("firstAccountTime") !=null)contract.setFirstAccountTime(sdf.parse(param.get("firstAccountTime").toString()));
		if(param.get("firstMngStartTime") !=null)contract.setFirstMngStartTime(sdf.parse(param.get("firstMngStartTime").toString()));
		if(param.get("serviceStartTime") !=null)contract.setServiceStartTime(sdf.parse(param.get("serviceStartTime").toString()));
		contract.setUpdateTime(new Date());
		String income=param.get("incomeArr")==null?"":param.get("incomeArr").toString();
		 if(income!=null && income !=""){
		 JSONArray incomeArr=com.alibaba.fastjson.JSONObject.parseArray(income);
		 for(int i=0;i<incomeArr.size();i++){
			 Object obj=incomeArr.get(i);
			 try {
				Map<String,Object> incomeMmap=(Map<String, Object>) ObjAndMapUtil.objectToMap(obj).get("innerMap");
				ExpectedFixedIncome expectIncome=new ExpectedFixedIncome();
				expectIncome.setExpectedEndTime(sdf.parse(incomeMmap.get("expectedEndTime").toString()));
				expectIncome.setExpectedStartTime(sdf.parse(incomeMmap.get("expectedStartTime").toString()));
				expectIncome.setIncome(Integer.valueOf(incomeMmap.get("income").toString()));
				contract.getExpectedFixedIncomeSet().add(expectIncome);
				expectIncome.setIncomeId("i-"+idWorker.nextId());
				contract.setExpectedFixedIncomeSet(contract.getExpectedFixedIncomeSet());
				expectIncome.setContract(contract);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		 }
		 String vacantPeriod=param.get("vacantPeriodArr")==null?null:param.get("vacantPeriodArr").toString();
		 if(vacantPeriod!=null){
		 JSONArray vacantPeriodArr=com.alibaba.fastjson.JSONObject.parseArray(vacantPeriod);
		 for(int i=0;i<vacantPeriodArr.size();i++){
			 Object obj=vacantPeriodArr.get(i);
			 try {
				Map<String,Object> vMmap=(Map<String, Object>) ObjAndMapUtil.objectToMap(obj).get("innerMap");
				VacantPeriod vacantPeriod1=new VacantPeriod();
				vacantPeriod1.setStartTime(sdf.parse(vMmap.get("startTime").toString()));
				vacantPeriod1.setEndTime(sdf.parse(vMmap.get("endTime").toString()));
				vacantPeriod1.setVid("v-"+idWorker.nextId());
				contract.getVacantPeriodSet().add(vacantPeriod1);
				contract.setVacantPeriodSet(contract.getVacantPeriodSet());
				vacantPeriod1.setContract(contract);
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		
		 }
		return contractService.updateConstract(contract);
	}
	/**
	 * 获取合同列表
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getContractList")
	@ResponseBody
	public Map<String,Object> getContractList(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		User user =(User) session.getAttribute("userModel");
		param.put("userId", user.getUserId());
		param.put("flag", user.getFlag());
		if(user.getFlag()==1){
			return contractService.getContractList(param);
		}else{
			return zuKeContractService.getContractList(param);
		}
		
	}
	
	/**
	 * 获取合同列表(管理员)
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getContractListForAdmin")
	@ResponseBody
	public Map<String,Object> getContractListForAdmin(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		param.put("flag", "0");
		return contractService.getContractList(param);
	}
	
	/**
	 * 签合同
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/signComtract")
	@ResponseBody
	public Map<String,Object> signComtract(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		return contractService.signComtract(param);
	}
	/**
	 * 获取租客名称
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("/getUserInfo")
	@ResponseBody
	public Map<String,Object> getUserInfo(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Map<String, Object> param = SpringUtils.getParameterMap(request);
		return null;
	}
}
